/**
 * Name:tool.js
 * Author:gene.jiang
 * E-mail:1013195469@qq.com
 * Website:http://www.jianggujin.com/
 * LICENSE:Apache v2 License
 * Description:工具集
 */
layui.define([], function(exports) {
    var tool = {
        /**
         * 加载层
         * @param {Number} type
         */
        load: function(type) {
            type = type || 0;
            return layer.load(type, {
                shade: [0.3, '#333']
            });
        },
        /**
         * 生成随机字符串
         * @param {String} prefix
         */
        makeHashCode: function(prefix) {
            var rhashcode = /\d\.\d{4}/;
            /* istanbul ignore next*/
            prefix = prefix || 'gene';
            /* istanbul ignore next*/
            return String(Math.random() + Math.random()).replace(rhashcode, prefix);
        },
        /**
         * 判断是否为底层方法
         * @param {Function} fn
         */
        isNative: function(fn) {
            return(/\[native code\]/.test(fn));
        },
        /**
         * 属性拷贝，浅拷贝
         * @param {Object} destination 目标对象
         * @param {Object} source 源对象
         */
        shadowCopy: function(destination, source) {
            for(var property in source) {
                destination[property] = source[property];
            }
            return destination;
        },
        /**
         * 判断两个数组是否相等
         * @param {Array} arr1
         * @param {Array} arr2
         * @return {Boolean}
         */
        arrayEqual: function(arr1, arr2) {
            if(arr1 === arr2)
                return true;
            if(arr1.length != arr2.length)
                return false;
            for(var i = 0; i < arr1.length; ++i) {
                if(arr1[i] !== arr2[i])
                    return false;
            }
            return true;
        },
        /**
         * cookie操作
         * @param {String} name
         * @param {String} value
         * @param {JSON} options
         */
        cookie: function(name, value, options) {
            // 写
            if(arguments.length > 1) {
                options = options || {};

                if(typeof options.expires === 'number') {
                    var days = options.expires,
                        t = options.expires = new Date();
                    t.setMilliseconds(t.getMilliseconds() + days * 864e+5);
                }

                return(document.cookie = [
                    name, '=', value,
                    options.expires ? '; expires=' + options.expires.toUTCString() : '', //使用expires属性, max-age不支持IE
                    options.path ? '; path=' + options.path : '',
                    options.domain ? '; domain=' + options.domain : '',
                    options.secure ? '; secure' : ''
                ].join(''));
            }

            // 读取
            var arr = document.cookie.replace(/\s/g, "").split(';');
            for(var i = 0; i < arr.length; i++) {
                var tempArr = arr[i].split('=');
                if(tempArr[0] == name) {
                    return tempArr[1];
                }
            }
            return undefined;
        },
        /**
         * 移除Cookie
         * @param {String} name
         */
        removeCookie: function(name) {
            tool.cookie(name, '', {
                expires: -1
            });
            return !tool.cookie(name);
        },
        /**
         * 获取浏览器类型和版本
         * @return {JSON}
         */
        getExplore: function() {
            var sys = {},
                ua = navigator.userAgent.toLowerCase(),
                s;
            (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? sys.ie = s[1]:
                (s = ua.match(/msie ([\d\.]+)/)) ? sys.ie = s[1] :
                (s = ua.match(/edge\/([\d\.]+)/)) ? sys.edge = s[1] :
                (s = ua.match(/firefox\/([\d\.]+)/)) ? sys.firefox = s[1] :
                (s = ua.match(/(?:opera|opr).([\d\.]+)/)) ? sys.opera = s[1] :
                (s = ua.match(/chrome\/([\d\.]+)/)) ? sys.chrome = s[1] :
                (s = ua.match(/version\/([\d\.]+).*safari/)) ? sys.safari = s[1] : 0;
            // 根据关系进行判断
            if(sys.ie)
                return {
                    name: 'IE',
                    version: sys.ie
                };
            if(sys.edge)
                return {
                    name: 'EDGE',
                    version: sys.edge
                };
            if(sys.firefox)
                return {
                    name: 'Firefox',
                    version: sys.firefox
                };
            if(sys.chrome)
                return {
                    name: 'Chrome',
                    version: sys.chrome
                };
            if(sys.opera)
                return {
                    name: 'Opera',
                    version: sys.opera
                };
            if(sys.safari)
                return {
                    name: 'Safari',
                    version: sys.safari
                };
            return {};
        },
        /**
         * 获取操作系统类型
         * @return {String}
         */
        getOS: function() {
            var userAgent = 'navigator' in window && 'userAgent' in navigator && navigator.userAgent.toLowerCase() || '';
            var vendor = 'navigator' in window && 'vendor' in navigator && navigator.vendor.toLowerCase() || '';
            var appVersion = 'navigator' in window && 'appVersion' in navigator && navigator.appVersion.toLowerCase() || '';
            if(/mac/i.test(appVersion))
                return 'mac';
            if(/win/i.test(appVersion))
                return /phone/i.test(userAgent) ? 'windowsPhone' : 'windows';
            if(/linux/i.test(appVersion))
                return 'linux';
            if(/iphone/i.test(userAgent) || /ipad/i.test(userAgent) || /ipod/i.test(userAgent))
                return 'ios';
            if(/android/i.test(userAgent))
                return 'android';
        },
        /**
         * 获得设备信息
         * @param {String} key
         */
        device: function(key) {
            var win = window,
                agent = navigator.userAgent.toLowerCase()
                //获取版本号
                ,
                getVersion = function(label) {
                    var exp = new RegExp(label + '/([^\\s\\_\\-]+)');
                    label = (agent.match(exp) || [])[1];
                    return label || false;
                }
                //返回结果集
                ,
                result = {
                    os: function() { //底层操作系统
                        return tool.getOS();
                    }(),
                    explore: function() {
                        return tool.getExplore();
                    }(),
                    ie: function() { //ie版本
                        return(!!win.ActiveXObject || "ActiveXObject" in win) ? (
                            (agent.match(/msie\s(\d+)/) || [])[1] || '11' //由于ie11并没有msie的标识
                        ) : false;
                    }(),
                    weixin: getVersion('micromessenger') //是否微信
                };

            //任意的key
            if(key && !result[key]) {
                result[key] = getVersion(key.toLocaleLowerCase());
            }

            return result;
        },
        /**
         * 动态加载CSS文件的方法
         *
         * @param {String}   fileName              CSS文件名
         * @param {Function} [callback=function()] 加载成功后执行的回调函数
         */
        loadCSS: function(href, callback) {
            callback = callback || function() {};

            var link = document.createElement("link");
            link.type = "text/css";
            link.rel = "stylesheet";
            link.media = 'all';
            link.onload = css.onreadystatechange = function() {
                callback(true, href);
            };
            link.onerror = function() {
                callback(false, href);
            };
            link.href = href;
            document.getElementsByTagName("head")[0].appendChild(css);
        },
        /**
         * 动态加载JS文件的方法
         *
         * @param {String}   src              JS文件名
         * @param {Function} [callback=function()] 加载成功后执行的回调函数
         */
        loadScript: function(src, callback) {
            callback = callback || function() {};

            var script = null;
            script = document.createElement("script");
            script.type = "text/javascript";
            script.src = src;
            script.onload = script.onreadystatechange = function(e) {
                if(e && e.type == 'load') {
                    callback(true, src);
                } else if(script.readyState) {
                    if(script.readyState === "loaded" || script.readyState === "complete") {
                        script.onreadystatechange = null;
                        callback(true, src);
                    }
                }
            };
            script.onerror = function() {
                callback(false, src);
            };
            document.getElementsByTagName("head")[0].appendChild(script);
        },
        /**
         * JS继承
         * @param {Object} Child
         * @param {Object} Parent
         */
        inherit: function(Child, Parent) {
            var F = function() {};
            F.prototype = Parent.prototype;
            Child.prototype = new F();
            Child.prototype.constructor = Child;
            Child.superclass = Parent.prototype;
        },
        /**
         * 打开地址
         * @param {JSON|String} attrs 表单参数
         * @param {JSON} params 请求参数
         */
        openBlank: function(attrs, params) {
            var form = document.createElement("form");
            form.style.display = "none";
            if(typeof attrs === 'string') {
                form.setAttribute("action", attrs)
            } else if(typeof attrs === 'object') {
                for(var a in attrs) {
                    form.setAttribute(a, attrs[a])
                }
            }
            if(typeof params === 'object') {
                for(var p in params) {
                    var input = document.createElement("input");
                    input.type = "hidden";
                    input.name = p;
                    input.value = params[p];
                    form.appendChild(input);
                }
            }
            document.body.appendChild(form);
            form.submit();
        },
        /**
         * 转换为连字符线风格
         * @param {String} target
         */
        hyphen: function(target) {
            var rhyphen = /([a-z\d])([A-Z]+)/g;
            return target.replace(rhyphen, '$1-$2').toLowerCase();
        },
        /**
         * 转换为驼峰风格
         * @param {String} target
         */
        camelize: function(target) {
            var rcamelize = /[-_][^-_]/g;
            //提前判断，提高getStyle等的效率
            if(!target || target.indexOf('-') < 0 && target.indexOf('_') < 0) {
                return target;
            }
            //转换为驼峰风格
            return target.replace(rcamelize, function(match) {
                return match.charAt(1).toUpperCase();
            });
        }
    };

    exports('tool', tool);
});